import axiosStatic, { AxiosInstance, AxiosRequestConfig } from 'axios'
import { Storage } from './common';
import { showFailToast } from 'vant';
interface ResponseData<T> {
  rows?: T,
  data?: T,
  code: number,
  msg: string,
  total?: number,
}

//读取全局配置
const AUTH_TOKEN = import.meta.env.VITE_APP_AUTH_TOKEN
// 配置新建一个 axios 实例
const axios: AxiosInstance = axiosStatic.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 20000,
  headers: { 'Content-Type': 'application/json' },
});
axiosStatic.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

// 请求 拦截器
axios.interceptors.request.use((config) => {
  let accessToken = Storage.get(AUTH_TOKEN)
  if (accessToken) {
    config.headers.Authorization = 'Bearer ' + accessToken
  }
  return config
}, (error) => {
  // Do something with request error
  return Promise.reject(error)
});

//响应拦截器
axios.interceptors.response.use(
  (response) => {
    console.log('response', response);
    const resData = response.data;
    // 未设置状态码则默认成功状态
    const code = resData.code || 200;
    const msg = resData.msg
    if (code !== 200) {
      showErrMsg(msg);
      return Promise.reject(msg || '未知错误')
    } else {
      return Promise.resolve(resData);
    }
  },
  (error) => {
    console.log('err', error)
    if (error.response) {
      if (error.response.status == 404) {
        showErrMsg("status:404,请求的资源不存在！");
      } else if (error.response.status == 500) {
        showErrMsg(error.response.data.message || "status:500,服务器发生错误！");
      } else if (error.response.status == 401) {
        showErrMsg(error.response.data.message || "status:401,服务器发生错误！");
      } else {
        showErrMsg(error.message || `status:${error.response.status},未知错误！`);
      }
    } else if (error.code == 'ERR_CANCELED') {
      //取消了
    } else {
      showErrMsg(error.message || '请求服务器无响应！');
    }
    // 请求错误时做些事
    return Promise.reject(error)
  }
)

function showErrMsg(errMsg: string) {
  showFailToast(errMsg ? errMsg : '当前网络不稳定,请稍后重试')

}
const request = <T = any>(config: AxiosRequestConfig): Promise<ResponseData<T>> => {
  return axios(config)
}

export {
  request
}

export default axios;